# Generic auxiliary functions
# (c) 2008-2009 NIXON Development Corporation.

import locale, datetime, time
		
def parseSize(size, bytes=False):
	size = float(size)
	if size == (-1):
		return '[folder]'
	else:
		# Just for fun, support every unit defined
		units = ('', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
		
		fs = -1
			
		for x in range(1, 10):
			if size < 1024 ** x or x == 9:
				fs = float(size / 1024 ** (x-1))
				unit = units[x - 1]
				break

		locale.setlocale(locale.LC_ALL, '')
		fs = locale.format('%.2f', fs, True)
		#size = locale.format('%d', size, True)
		size = str(size)
		
		if unit == '':
			return size + ' bytes'
		else:
			strSize = fs + ' ' + unit
			if bytes:
				strSize += ' (%s bytes)' % size
				
			return strSize

def parseDate(dt, relative=False, filter=''):
	if filter == '':
		strFilter = '%A, %d %B %Y  %H:%M'
	else:
		strFilter = filter
		
	if not relative:
		return time.strftime(strFilter, dt)
	else:
		dtdate = datetime.date(dt[0], dt[1], dt[2])
		nowdate = datetime.datetime.now().date()
		diff = nowdate - dtdate
		
		if diff.days < 0: # Date set wrong
			return time.strftime(strFilter, dt)
			
		elif diff.days == 0: # Today
			diffsecs = int(time.time() - time.mktime(dt))
			if diffsecs < 0: # Future
				return time.strftime(strFilter, dt)
				
			if diffsecs < 60:
				return  '%d seconds ago' % (diffsecs)
			elif diffsecs < 3600:
				ds = diffsecs / 60
				if ds == 1: strS = ''
				else: strS = 's'
				
				return '%d minute%s ago' % (ds, strS)
			else:
				ds = int(diffsecs / 3600)
				if ds == 1: 	strH = 'hour'
				else: strH = 'hours'
				
				return '%d %s ago' % (diffsecs / 3600, strH)
		elif diff.days < 7: # This week
			if diff.days == 1: return 'Yesterday'
			else: return '%d days ago' % diff.days
			
		elif diff.days < 31: # This month
			weeks = diff.days / 7
			if weeks == 1: return 'a week ago'
			else: return '%d weeks ago' % weeks
			
		elif diff.days < 366: # This year
			months = diff.days / 30
			if months == 1: return 'a month ago'
			else: return '%d months ago' % months
		else: # Before this year
			years = diff.days / 365
			months = (diff.days % 365) / 30
			
			if months == 1: strMonths = ', 1 month'
			elif months != 0: strMonths = ', %d months' % months
			else: strMonths = ''
				
			if years == 1: strYears = ''
			else: strYears = 's'
				
			return '%d year%s%s ago' % (years, strYears, strMonths)
			
def parseTime(secs, short=False):
	try: secs = long(secs)
	except: return 'Unknown'
	
	ds = (60, 3600, 86400, 604800, 31556952)
	if short:
		ts = ('',':',':','d ','w ','a ')
	else:
		ts = (' seconds',' minutes ',' hours ',' days ',' weeks ',' years ')
	
	for x in range(5):
		if secs < ds[x]:
			if secs < 60:
				s = ts[0]
				if not short:
					if secs == 1:
						s = ts[0][:-1] + ' '
					elif secs == 0: return ''
				
				return str(secs) + s
			else:
				units = secs / ds[x-1]
				s = ts[x]
				if not short:
					if units == 1:
						s = ts[x][:-2] + ' '
					elif units == 0: return ''
				
				return str(units) + s + parseTime(secs % ds[x-1], short)
				
	units = secs / ds[4]
	s = ts[5]
	if not short:
		if units == 1: # plural to singular
			s = ts[5][:-2] + ' '
		elif units == 0: return ''
	
	return str(units) + s + parseTime(secs % ds[4], short)
	
def remain(secs, finished, total):
	try:
		secs = long(secs)
		finished = long(finished)
		total = long(total)
	except: return 'Unknown'
	
	flFin = float(finished)
	flSecs = float(secs)
	
	if flFin == 0 or flSecs == 0:
		return 0
	else:
		rate = flFin / flSecs
		return (total - finished) / rate
			
def getRealName(handle, dir, fname, local):
	if not local:
		pwf = dir + '/' + fname
		name = handle.dirList.getReals(pwf)
	
	sep = fname.find(' -> ')
	if sep != -1:
		fname = fname[:sep]
		
	return fname
	
def getNameFromPath(path, reverse=False):
	pos = -1
	for x in ('/','\\',':'):
		pos = path.rfind(x)
		if pos <> -1:
			break

	if reverse:
		if pos == 0:
			ret = path[:1]
		else:
			ret = path[:pos]
	else:
		if pos == len(path) - 1:
			ret = path[:-1]
		else:
			ret = path[pos + 1:]
		
	return ret
	
def shorten(s, amt):
	if amt >= len(s): return s
	intShort = int(amt / 2)
	return s[:intShort] + '..' + s[-intShort:]
	